//
//  HMHomeTableViewController.m
//  SinaWeiBo
//
//  Created by WGP on 16/4/9.
//  Copyright © 2016年 WGP. All rights reserved.
//


//导航条上显示什么取决于子类控制器
#import "HMHomeTableViewController.h"
#import "UIBarButtonItem+Extension.h"
#import "HMUserAccountViewModel.h"
#import "HMTitleBtn.h"
#import "HMStatuses.h"
#import "HMStatusesViewModel.h"
#import "HMStatusCell.h"
#import "HMUserAccount.h"
#import "HMPullDownRefreshControl.h"
#import <SVPullToRefresh.h>

@interface HMHomeTableViewController ()

@property(nonatomic,strong)NSMutableArray *statuses;
@property(nonatomic,strong)HMPullDownRefreshControl *myRefreshControl;
@property(nonatomic,strong)UILabel *tipLabel;

@end

static NSString *ReuseIdentifier = @"csjgfjahsgfhjgaskell";

@implementation HMHomeTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    当显示的事访客视图的时候,应该返回,在swift里不判断会崩
    if (![[HMUserAccountViewModel sharedInstance] userLogin])
    {
        return ;
    }
    
    [self setupNavItems];
    

    [self prepareForTableView];
    
}

#pragma mark - tableView的一些准备情况
-(void)prepareForTableView
{
    //    注册cell
    
    [self.tableView registerClass:[HMStatusCell class] forCellReuseIdentifier:ReuseIdentifier];
    
    //    1.让tableView能自动适应
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    ////     2.给一个预估值
//    self.tableView.estimatedRowHeight = 20;
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    
    self.myRefreshControl = [[HMPullDownRefreshControl alloc] init];
    
    __weak typeof(self) weakSelf = self;
    self.myRefreshControl.actionHandleBlock = ^
    {
        //        加载更多数据
        [weakSelf loadNewStatus];
    };
    [self.tableView addSubview:self.myRefreshControl];
    
    [self.myRefreshControl startRefreshing];
}

#pragma mark - 加载新数据
-(void)loadNewStatus
{
    HMStatuses *firstStatus = [self.statuses firstObject];
    
    int64_t since_id = firstStatus.Id;
    
    [[HMStatusesViewModel sharedInstance] loadUserDataWithSince_id:since_id max_id:0 finished:^(NSArray *statuses, NSError *error) {
        
//        加载数据回调后应该结束刷新
        [self.myRefreshControl stopRefreshing];
        
        if(error != nil)
        {
            HMLog(@"获取微博数据出错:%@",error);
            [SVProgressHUD showErrorWithStatus:@"您的网络不给力!"];
            return ;
        }
        
        NSInteger count = statuses.count;
        
        if (since_id != 0) {
//            用户手动拖拽,现实下拉刷新的条数
            [self showTipLabelWith:count];
        }
        
        if (count == 0) {
            if (since_id == 0)
            {
                [SVProgressHUD showErrorWithStatus:@"没有加载到数据!"];
            }
            return ;
        }
        
        __weak typeof(self) weakSelf = self;
        if (since_id == 0)
        {
            self.statuses = [NSMutableArray arrayWithArray:statuses];
            [self.tableView addInfiniteScrollingWithActionHandler:^{

//                上拉加载数据
                [weakSelf loadMoreStatus];
            }];
            
        }else
        {
            NSMutableArray *arr = [NSMutableArray arrayWithArray:statuses];
            [arr addObjectsFromArray:weakSelf.statuses];
            weakSelf.statuses = arr;
        }
        
    }];
}

-(void)loadMoreStatus
{
//    获得id最小的微博
    HMStatuses *lastStatus = self.statuses.lastObject;
    int64_t max_id = lastStatus.Id;
    
//    没有微博数据,就不去上拉刷新
    if (max_id == 0)
    {
        return ;
    }
    
//    加载比max_id还小的微博
    [[HMStatusesViewModel sharedInstance] loadUserDataWithSince_id:0 max_id:max_id finished:^(NSArray *statuses, NSError *error) {
       
//        让控件刷新结束
        [self.tableView.infiniteScrollingView stopAnimating];
        
        if (error != nil) {
            HMLog(@"上拉加载更多微博数据失败:%@",error);
            return ;
        }
        
        NSInteger count = statuses.count;
        
        if (count == 0) {
            [SVProgressHUD showErrorWithStatus:@"没有加载到更多数据"];
            return ;
        }
        
//        拼接数据
        [self.statuses addObjectsFromArray:statuses];
        [self.tableView reloadData];
    }];
}

-(void)showTipLabelWith:(NSInteger)count
{
    CGFloat y = -([UIApplication sharedApplication].statusBarFrame.size.height + TipLabelHeight);
    CGFloat tiplabelWidth = [UIScreen mainScreen].bounds.size.width;
    
//    label是加到导航栏里的,y = -(状态栏的高度 + 导航栏的高度)
    self.tipLabel.frame = CGRectMake(0, y,tiplabelWidth , TipLabelHeight);
    
    self.tipLabel.text = count == 0 ? @"没有新的微博" : [NSString stringWithFormat:@"刷新了%zd条微博",count];
    
//    快速拖动,会发现动画还没有完成,又来一个动画,动画叠加
//    UIView动画,底层其实也是一个核心动画
//    获取layer上面正在执行动画的key
    
    if (self.tipLabel.layer.animationKeys)
    {
        HMLog(@"正在tipLabel执行动画");
        return ;
    }
    
//    控制器一直存在一个label,动画完成不移除,只是用户看不到
    [UIView animateWithDuration:1 animations:^{
        
        self.tipLabel.frame = CGRectMake(0, TipLabelHeight, tiplabelWidth, TipLabelHeight);
        
    } completion:^(BOOL finished) {
//        停一会,再动画回到屏幕上面去
//        返回回去的动画
        
        [UIView animateWithDuration:1 animations:^{
            
            self.tipLabel.frame = CGRectMake(0, y, tiplabelWidth, TipLabelHeight);
        }];
    }];
}

-(void)setStatuses:(NSMutableArray *)statuses
{
    _statuses = statuses;
    [self.tableView reloadData];
}

#pragma mark - 设置导航条按钮
-(void)setupNavItems
{
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem customViewWith:@"navigationbar_friendsearch" target:self action:@selector(leftItemDidClick)];
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem customViewWith:@"navigationbar_pop" target:self action:@selector(rightItemDidClick)];
    
    NSString *title = [HMUserAccountViewModel sharedInstance].userAccount.screen_name;
    
    HMTitleBtn *titleBtn = [HMTitleBtn titleBtnWith:title imageName:@"navigationbar_arrow_down"];
    self.navigationItem.titleView = titleBtn;
    
    [titleBtn addTarget:self action:@selector(titleViewDidClick:) forControlEvents:UIControlEventTouchDown];
    
}

#pragma mark - 按钮事件

-(void)leftItemDidClick
{
//    HMLog(@"leftItemDidClick");
}

-(void)rightItemDidClick
{
//    HMLog(@"rightItemDidClick");
}

-(void)titleViewDidClick:(HMTitleBtn *)titlBtn
{
    titlBtn.selected = !titlBtn.selected;
    [titlBtn startAnimation];
}

#pragma mark - 数据源方法

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.statuses.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    HMStatusCell *cell = [tableView dequeueReusableCellWithIdentifier:ReuseIdentifier forIndexPath:indexPath];
    HMStatusCell *cell = [tableView dequeueReusableCellWithIdentifier:ReuseIdentifier];
    HMStatuses *status = self.statuses[indexPath.row];
    cell.status = status;
    return cell;
}

-(BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath
{
    return NO;
}

//tableView在cell显示之前会调用heightForRowAtIndexPath,有多少个cell就调用多少次

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    获取模型
    HMStatuses *status = self.statuses[indexPath.row];
//    判断模型里面之前有没有缓存过行高
    if (status.cellHeight != 0) {
//        之前把存过行高,直接返回行高
//        NSLog(@"%f------%zd",status.cellHeight,indexPath.row);
        return status.cellHeight;
    }
    
//    自己计算行高:AutoLayout自动约束,让cell设置对应的内容,就可以直接获得高度,这个cell并不一定要显示
    HMStatusCell *cell = [tableView dequeueReusableCellWithIdentifier:ReuseIdentifier];
    cell.status = status;
    
    CGFloat cellHeight = [cell systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
    status.cellHeight = cellHeight;
    
//    NSLog(@"%f------%zd",cellHeight,indexPath.row);
    return cellHeight;
}

#pragma mark - 懒加载
-(UILabel *)tipLabel
{
    if(_tipLabel == nil)
    {
        self.tipLabel = [[UILabel alloc] init];
        
        self.tipLabel.backgroundColor = [UIColor orangeColor];
        self.tipLabel.textAlignment = NSTextAlignmentCenter;
        
//        吧提示label添加到导航条上
        [self.navigationController.navigationBar insertSubview:_tipLabel atIndex:0];
    }
    return _tipLabel;
}

@end












